//
//  ST_CommentInputBar.swift
//  btvideo
//
//  Created by mac on 2020/5/27.
//  Copyright © 2020 JarvanZhang. All rights reserved.
//

import UIKit
import SwifterSwift
import SnapKit
import ISEmojiView

class ST_CommentInputBar: UIView {
    
    static let height = 150
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        self.backgroundColor = .white
        self.alpha = 0
        
        self.addSubview(textView)
        textView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview().inset(UIEdgeInsets.init(top: 12, left: 10, bottom: 32+10+10, right: 15))
        }
        
        self.addSubview(text_place_holder_label)
        
        text_place_holder_label.snp.makeConstraints { (make) in
            make.top.equalTo(textView).offset(8)
            make.left.equalTo(textView).offset(5)
            make.right.equalTo(textView)
        }
        
        self.addSubview(current_text_count_label)
        current_text_count_label.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(15)
            make.bottom.equalToSuperview().offset(-10)
        }
        self.addSubview(sendBtn)
        sendBtn.snp.makeConstraints { (make) in
            make.right.equalToSuperview().offset(-5)
            make.bottom.equalToSuperview()
            make.height.equalTo(44)
            make.width.equalTo(52)
        }
        
        
        NotificationCenter.default.addObserver(forName: UIResponder.keyboardWillShowNotification, object: nil, queue: OperationQueue.main) {[weak self] (notification) in
            
            self?.key_broad_height_changed(notification: notification)
            
        }
        
        NotificationCenter.default.addObserver(forName: UIResponder.keyboardWillHideNotification, object: nil, queue: OperationQueue.main) {[weak self] (notification) in
         
            self?.keyBroadHiddenHandle()
            
        }
        
    }
    
    deinit {
        
        NotificationCenter.default.removeObserver(self)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
//    MARK: - OutSide Properties
    var replyUserId:String?
    
    var commentId:String?
    
    /**
     新增
     */
    var groupId:String?
    
    /**
     默认验证人脸
     */
    var determinFace = true
    
    var onlyInputEmoji = false{
        didSet{
            
            if determinFace && FACE_AVATAE_STATE != 3{
                
                self.textView.inputView = self.emojiView
                self.text_place_holder_label.attributedText = disDetectedFaceEmojiPlaceHolderString
                
            }else if onlyInputEmoji{
                
                textView.inputView = self.emojiView
                
                text_place_holder_label.attributedText = normalEmojiPlaceHolderString
            }else{
                
                textView.inputView = nil
                self.text_place_holder_label.attributedText = normal_place_holder_string
            }
        }
    }
    
//    MARK: - Properties
    fileprivate lazy var textView:UITextView = {
       let control = UITextView()
        control.textColor = UIColor.init(hex: 0x61666F)
        control.tintColor = UIColor.init(hex: 0x61666F)
        control.font = UIFont.systemFont(ofSize: 16, weight: UIFont.Weight.regular)
        control.delegate = self
        return control
    }()
    
    
    fileprivate lazy var emojiView:EmojiView = {
        
        let keyboardSettings = KeyboardSettings(bottomType: BottomType.categories)
        keyboardSettings.countOfRecentsEmojis = 12
        keyboardSettings.updateRecentEmojiImmediately = true
        let emojiView = EmojiView(keyboardSettings: keyboardSettings)
        emojiView.translatesAutoresizingMaskIntoConstraints = false
        emojiView.delegate = self
        return emojiView
    }()
    
   fileprivate let place_holder_attr: [NSAttributedString.Key : Any] = [.font: UIFont.systemFont(ofSize: 16),.foregroundColor: UIColor(red: 0.67, green: 0.71, blue: 0.75, alpha: 1)]
    
    fileprivate lazy var normal_place_holder_string:NSAttributedString = {
        
        let attrString = NSMutableAttributedString(string: "说说你的意见吧~")
        
         attrString.addAttributes(place_holder_attr, range: NSRange(location: 0, length: attrString.length))
        
        return attrString
    }()
    
    fileprivate lazy var normalEmojiPlaceHolderString:NSAttributedString = {
        
        let attrString = NSMutableAttributedString(string: "该特质只支持emoji评论")
        
         attrString.addAttributes(place_holder_attr, range: NSRange(location: 0, length: attrString.length))
        
        return attrString
    }()
    
    fileprivate lazy var disDetectedFaceEmojiPlaceHolderString:NSAttributedString = {
        
        let attrString = NSMutableAttributedString(string: "未真人认证只能使用emoji评论")
        
         attrString.addAttributes(place_holder_attr, range: NSRange(location: 0, length: attrString.length))
        
        return attrString
    }()
    
    
    fileprivate lazy var text_place_holder_label:UILabel = {
       
        let control = UILabel()
      
        control.attributedText = normal_place_holder_string
        
        return control
    }()
    
    fileprivate lazy var current_text_count_label:UILabel = {
       
        let control = UILabel()
        control.textColor = UIColor.init(hex: 0xACB4C0)
        control.font = UIFont.systemFont(ofSize: 12)
        control.text = "还有\(maxCount)字"
        return control
    }()
    
    fileprivate lazy var sendBtn:UIButton = {
        
        let control = UIButton.init(type: UIButton.ButtonType.custom)
        control.setTitleForAllStates("发送")
        control.setTitleColor(UIColor.init(hex: 0xACB4C0)!, for: UIControl.State.normal)
        control.setTitleColor(UIColor.init(hex: 0x4685FC)!, for: UIControl.State.selected)
        control.addTarget(self, action: #selector(send_handle), for: UIControl.Event.touchUpInside)
        return control
    }()
    
    fileprivate var maxCount = 400

    var endEditClosure:((_ text:String,_ replyUserId:String?,_ commentId:String?)->())?
    
    var receiveCommentModel:ST_ReceiveCommentsCellModel?
    
    var keyBroadHiddenClosure:(()->())?
    
    var keyBroadShowClosure:(()->())?
}

extension ST_CommentInputBar:EmojiViewDelegate{
    
    func emojiViewDidPressSendButton(_ emojiView: EmojiView) {
        
        if self.textView.text.count < 1{
            return
        }
        
        self.endEditClosure?(self.textView.text,self.replyUserId,self.commentId)

        self.textView.text = ""
        
        self.replyUserId = nil
        
        self.commentId = nil
    }
    
    func emojiViewDidSelectEmoji(_ emoji: String, emojiView: EmojiView) {
        
        if NoSupportEmojis.contains(emoji){
            return
        }
        
        
        textView.insertText(emoji)
        
        sendBtn.isSelected = true
        
    }
    
    func emojiViewDidPressChangeKeyboardButton(_ emojiView: EmojiView) {
        textView.inputView = nil
        textView.returnKeyType = .send
        textView.reloadInputViews()
    }
    
    func emojiViewDidPressDeleteBackwardButton(_ emojiView: EmojiView) {
        textView.deleteBackward()
        sendBtn.isSelected = !textView.text.isEmpty
    }
    
    func emojiViewDidPressDismissKeyboardButton(_ emojiView: EmojiView) {
        textView.resignFirstResponder()
    }
    
}

extension ST_CommentInputBar:UITextViewDelegate{
    
    
    func textViewDidChange(_ textView: UITextView) {
        text_place_holder_label.isHidden = !textView.text.isEmpty
    }
    
    func textViewDidBeginEditing(_ textView: UITextView) {
        text_place_holder_label.isHidden = !textView.text.isEmpty
    }
    
    func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
        
        if onlyInputEmoji || FACE_AVATAE_STATE != 3,let pas = UIPasteboard.general.string ,pas == text{
//            self.parentViewController?.toast(text: "")
            return false
        }
        
            
        guard var animal = textView.text else{
            return true
        }
        
        if let idxRange = Range.init(range, in: animal){
            
            animal.replaceSubrange(idxRange, with: text)
            
            var residueCount = maxCount - animal.count
            
            if residueCount < 0{
                residueCount = 0
            }
            
            var displayCount = animal.count
            
            if displayCount > maxCount{
                displayCount = maxCount
            }
            
            sendBtn.isSelected = displayCount > 0
            
            current_text_count_label.text = "还有\(maxCount-displayCount)字"
            
            return animal.count <= maxCount
            
        }else{
            return true
        }
    }
}

extension ST_CommentInputBar{
    
    func startEdit(){
        
        self.startEdit(replyUserId: nil, commentId: nil,nickName: nil)
    }
    
    func startEdit(replyUserId:String?,commentId:String?,nickName:String?){
        
        
        self.replyUserId = replyUserId
        
        self.commentId = commentId
        
        self.textView.becomeFirstResponder()
        
        if let name = nickName{
            
            let attrString = NSMutableAttributedString(string: "回复 \(name)：")
            
             attrString.addAttributes(place_holder_attr, range: NSRange(location: 0, length: attrString.length))
            
            self.text_place_holder_label.attributedText = attrString
            
        }else{
            
            
            if onlyInputEmoji{
                self.text_place_holder_label.attributedText = normalEmojiPlaceHolderString
            }else{
                self.text_place_holder_label.attributedText = normal_place_holder_string
            }
        }
        
    }
    
    @objc fileprivate func send_handle(){
        
        if !self.sendBtn.isSelected{
            return
        }
        
        
        self.endEditClosure?(self.textView.text,self.replyUserId,self.commentId)

        self.textView.text = ""
        
        self.replyUserId = nil
        
        self.commentId = nil
    }
    
    
    func key_broad_height_changed(notification:Notification){
        
        if !self.textView.isFirstResponder{
            return
        }
        
        self.keyBroadShowClosure?()
        
        if let keyboardFrame: NSValue = notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue {
            
            let keyboardRectangle = keyboardFrame.cgRectValue
            
            let keyboard_height = keyboardRectangle.height
            
            
            UIView.animate(withDuration: 0.25, animations: {
                
                self.alpha = 1
                
                self.transform = CGAffineTransform.init(translationX: 0, y: -keyboard_height)
                
            }) { (f) in
                
            }
        }
    }
    
    func keyBroadHiddenHandle(){
        
        self.keyBroadHiddenClosure?()
        
        UIView.animate(withDuration: 0.25, animations: {
            
            self.alpha = 0
            
            self.transform = CGAffineTransform.identity
            
        }) { (f) in
            
        }
        
    }
}



let NoSupportEmojis = ["0️⃣","1️⃣","2️⃣","3️⃣","4️⃣","5️⃣","6️⃣","7️⃣","8️⃣","9️⃣","🔟"]
